/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.fb.visualization;

import infomanagers.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.restfb.FacebookClient;
import com.restfb.DefaultFacebookClient;
import com.restfb.types.User;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
 *
 * @author Mato, Lenka
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet 
{
    
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");      
        getAccesToken(request, response);

    }
    
    /**
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void getAccesToken(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {

        String code = request.getParameter("code");
        String fbGetTokenAddress = "https://graph.facebook.com/oauth/access_token?client_id=" + AuthorizationServlet.appId + "&redirect_uri=" + AuthorizationServlet.appURL + "&client_secret="
+ AuthorizationServlet.appSecret + "&code=" + code;
       
        URL url = new URL(fbGetTokenAddress);
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        String [] tokens = br.readLine().split("&");
        String [] gottenTokens = tokens[0].split("=");
        String token = gottenTokens[1];
        FacebookClient fbClient = new DefaultFacebookClient(token);
       
        BasicUserInfoManager infoManager = new BasicUserInfoManager(fbClient);
        
        try
        {
            XMLGenerator xmlGenerator = new XMLGenerator(infoManager);
            xmlGenerator.generateXML();
            response.sendRedirect("visualization.html");
        }
        catch(IllegalArgumentException e)
        {
            System.out.println("Error - cannot generate XML because info manager is null");
        }
        
       /* for(User friend : infoManager.getFriends())
        {
            System.out.println(friend.getName() + "'s mutual friends(" + infoManager.getMutualFriends(friend).size()+"):");
            for(User u : infoManager.getMutualFriends(friend))
            {
                System.out.println(u.getName());
            }
        }*/
        
        //example of HTML output - but we are not going to do it this way
        /*PrintWriter out = response.getWriter();
        try 
        {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>" + infoManager.getUserName()+ "</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1 style=\"font-family: Arial, Tahoma; font-size: 13px; font-weight: bold;\"> List of " + infoManager.getUserName()  + "`s friends and their hometowns (" + infoManager.getFriends().size() + "friends, "+ infoManager.getMaleFriends().size() + " male and " + infoManager.getFemaleFriends().size() +" female" +")</h1>");
            out.println("<ul>");
            for(User u : infoManager.getFriends())
            {
            //    out.println("<li style=\"font-family: Arial, Tahoma; font-size: 10px\">" + u.getName() + ", from: "+ /*u.getGender() + u.getHometownName() + "</li>");
            }
            out.println();
            out.println("<h2 style=\"font-family: Arial, Tahoma; font-size: 12px; font-weight: bold;\">" + "List of places where your friends live: </h2>");
            for(String place : infoManager.getFriendsPlaces().keySet())
            {
                out.println("<li style=\"font-family: Arial, Tahoma; font-size: 10px\">" + place + ": " + infoManager.getFriendsPlaces().get(place) + "</li>");
            }
            out.println("</ul>");
            
            out.println("</body>");        
            out.println("</html>");
        } finally 
        {            
            out.close();
        } */
        

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
